//
//  AddressChooseViewController.m
//  B2C
//
//  Created by 李小龙 on 2017/8/10.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "AddressChooseViewController.h"
#import "AddressManageViewController.h"
#import "AddressChooserTableViewCell.h"
#import "AddressModel.h"

@interface AddressChooseViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
{
    UIButton *_tempSelect;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *tableArray;
@property (nonatomic, assign) NSInteger page;
@end

@implementation AddressChooseViewController
#pragma mark - Get
- (NSMutableArray *)tableArray {
    if (!_tableArray) {
        _tableArray = [[NSMutableArray alloc] init];
    }
    return _tableArray;
}
#pragma mark - UIViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"选择收货地址";
    [self hiddenShadowImage:NO];
    
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"管理" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemAction:)];
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIColor colorWithHex:0x030303 alpha:1.0] forKey:NSForegroundColorAttributeName];
    [right setTitleTextAttributes:dic forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = right;
    
    [self createTableView];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self getNetData];
}
- (void)disMissSelf {
    [super disMissSelf];
    if (self.block && _tempSelect && self.tableArray.count>_tempSelect.tag-100) {
        self.block(self.tableArray[_tempSelect.tag-100]);
    }
}
#pragma mark - action
- (void)rightBarButtonItemAction:(id)sender {
    AddressManageViewController *addressEditVC = [[AddressManageViewController alloc] init];
    addressEditVC.isShopcartNew = self.isShopcartNew;
    [self.navigationController pushViewController:addressEditVC animated:YES];
}

static NSString *addressChooseIdentifier = @"addressChooseIdentifier";
- (void)createTableView {
    self.page = 1;
    
    [self.tableView clearExtendCellLine];
    [self.tableView registerNib:[UINib nibWithNibName:@"AddressChooserTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:addressChooseIdentifier];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 1;
        [self getNetData];
    }];
    
//    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        _page++;
//        [self getNetData];
//    }];
//    [self.tableView.mj_footer setHidden:YES];
}
- (void)endRefresh {
    [self.tableView.mj_header endRefreshing];
//    [self.tableView.mj_footer endRefreshing];
}
- (void)getNetFailure {
    if (self.page != 1) {
        _page--;
    }
}
#pragma mark - 网络请求
- (void)getNetData {
    
    [MYAFNetworking POST:URL_Get_Address parameters:@{@"pageSize":@"1000",@"pageNumber":@(self.page)} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self endRefresh];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            NSDictionary *dics = responseObject;
//            if ([dics[@"pagenation"][@"totalCount"] integerValue] > self.tableArray.count) {
//                [self.tableView.mj_footer setHidden:NO];
//            } else {
//                [self.tableView.mj_footer setHidden:YES];
//            }
            
            if (_page == 1) {
                [self.tableArray removeAllObjects];
//                [self.tableView.mj_footer resetNoMoreData];
            }
            // 数据列表
            NSArray *arr = dics[@"data"][@"list"];
            if (arr.count == 0 && _page != 1) {
//                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                [self getNetFailure];
                return;
            }
            BOOL haveSelect = NO;
            for (NSDictionary *dataDic in arr) {
                AddressModel *model = [AddressModel mj_objectWithKeyValues:dataDic];
                [self.tableArray addObject:model];
                
                if (model.isdefault) {
                    [UserInfo shareInstance].user.defaultAddress = model;
                    [[UserInfo shareInstance] updateUserModel];
                }
                if ([model isEqual:[arr lastObject]] && ![UserInfo shareInstance].user.defaultAddress) {
                    [UserInfo shareInstance].user.defaultAddress = [arr firstObject];
                    [[UserInfo shareInstance] updateUserModel];
                }
                if ([self.selectModel.daid isEqualToString:model.daid]) {
                    haveSelect = YES;
                }
            }
            if (!haveSelect) {
                self.selectModel = self.tableArray.firstObject;
            }
            [self.tableView reloadData];
            
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
            [self getNetFailure];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [self endRefresh];
        [self getNetFailure];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AddressChooserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:addressChooseIdentifier forIndexPath:indexPath];
    AddressModel *model = self.tableArray[indexPath.row];
    
    // 收货人姓名
    [cell.nameLabel setText:model.daname];
    // 手机号
    [cell.phoneLabel setText:[LXLIsPhoneNumber phoneNumber:model.datel]];
    // 详细地址
    [cell.addressLabel setText:[NSString stringWithFormat:@"%@ %@ %@ %@",model.pname,model.cname,model.aname,model.daaddress]];
    // 选中按钮
    if ([model.daid isEqualToString:self.selectModel.daid]) {
        [cell.selectButton setSelected:YES];
        _tempSelect = cell.selectButton;
    } else {
        [cell.selectButton setSelected:NO];
    }
    [cell.selectButton setTag:indexPath.row+100];
    // 是否默认
    if (!model.isdefault) {
        [cell.defaultLabel setHidden:YES];
        //cell.defaultWLayout.constant = 0;
    } else {
        [cell.defaultLabel setHidden:NO];
        //cell.defaultWLayout.constant = 34.0;
    }
    
    //[cell.contentView layoutIfNeeded];
    
    cell.block = ^(NSInteger tag) {
        [_tempSelect setSelected:NO];
        _tempSelect = cell.selectButton;
        [_tempSelect setSelected:YES];
        
        self.selectModel = self.tableArray[tag-100];
//        if (self.block) {
//            self.block(self.tableArray[tag-100]);
//            [self disMissSelf];
//        }
    };
    
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"暂无地址"
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    _page = 1;
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self getNetData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
